<template>
  <div class="home-page">
    <el-table :data="scripts" style="width: 100%; margin-top: 10px;" v-if="scripts.length > 0">
      <el-table-column type="index" label="序号" align="center" width="55" />
      
      <el-table-column property="scriptId" label="脚本编号" align="center" />
      
      <el-table-column property="scriptName" label="脚本名称" align="center" />
      
      <el-table-column property="scriptContent" label="脚本内容" align="center" />

      <el-table-column label="脚本启动状态" align="center">
        <template #default="scope">
          <span>{{ scope.row.used === 1 ? '已启动' : '未启动' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="startScript(scope.row)">
            <el-icon>
              <EditPen />
            </el-icon> 启动
          </el-button>
          <el-button link type="primary" size="small" @click="handleUpdate(scope.row)">
            <el-icon>
              <EditPen />
            </el-icon> 编辑
          </el-button>
          <el-button link type="primary" size="small" @click="deleteScript(scope.row)">
            <el-icon>
              <Delete />
            </el-icon> 删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-else class="no-data-message">
      <el-empty description="还没有配置脚本，请先配置脚本。" />
    </div>
    
    <el-dialog v-model="showDialog" :title="dialogTitle" width="500">
      <component :is="showComp" v-if="showComp" :scriptId="showScriptId" @refreshEvent="handleRefresh"></component>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import ScriptEdit from './edit.vue';
import { ElMessage } from 'element-plus';

const scripts = ref([]); // 使用 ref 初始化为空，后续从后端获取
const showDialog = ref(false); // 初始化弹窗
const dialogTitle = ref(''); // 弹窗标题
const showComp = ref(null); // 动态切换组件
const showScriptId = ref(null); // 传递的scriptId参数

// 监听页面挂载并获取脚本数据
onMounted(() => {
  fetchScripts();
});

const fetchScripts = async () => {
  try {
    const userName = localStorage.getItem('user_name');
    const response = await axios.get(`/api/script/script/name/${userName}`);
    scripts.value = response.data.data; 
  } catch (error) {
    console.error('获取脚本失败:', error);
    ElMessage.error('获取脚本失败，请重试。');
  }
};

const startScript = async (script) => {
  try {
    const response = await axios.post(`/api/script/script/start/${script.scriptId}`);
    ElMessage.success(`启动脚本: ${script.scriptName}`);
    const updatedScript = {
      ...script, 
      used: 1 // 更新启动状态为1
    };
    const updateResponse = await axios.put('/api/script/script/edit', updatedScript);
	fetchScripts();
    if (updateResponse.data.code === 200) {
      ElMessage.success('脚本状态更新成功');
    } else {
      ElMessage.error('脚本状态更新失败');
    }
  } catch (error) {
    console.error('启动脚本失败:', error);
    ElMessage.error('启动脚本失败，请重试。');
  }
};

// 监听点击修改按钮时执行的方法
const handleUpdate = (row) => {
  showDialog.value = true;
  dialogTitle.value = '修改脚本';
  showComp.value = ScriptEdit;
  showScriptId.value = row.scriptId;
};

// 监听新增或修改子组件回调刷新
const handleRefresh = () => {
  showDialog.value = false;
  showScriptId.value = null;
  fetchScripts(); // 刷新脚本信息列表
};

const deleteScript = async (row) => {
  try {
    await axios.delete(`/api/script/script/${row.scriptId}`);
    scripts.value = scripts.value.filter(script => script.scriptId !== row.scriptId);
    ElMessage.success(`删除脚本 ID: ${row.scriptId}`);
  } catch (error) {
    console.error('删除脚本失败:', error);
    ElMessage.error('删除脚本失败，请重试。');
  }
};

</script>

<style scoped>
.home-page {
  padding: 20px;
}

.no-data-message {
  text-align: center; /* 中心对齐 */
  padding: 20px; /* 顶部和底部留白 */
}
</style>